package com.franklin.ideaplugin.mybatisrunner.xml.params;

import com.franklin.ideaplugin.mybatisrunner.event.events.AbstractSqlEvent;
import com.franklin.ideaplugin.mybatisrunner.event.events.UpdateTestEvent;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.psi.PsiElement;
import com.intellij.util.ui.FormBuilder;

import javax.swing.*;
import java.util.List;

/**
 * @author Ye Junhui
 * @since 2024/2/20
 */
public class ChooseParam extends MybatisParam {

    private ComboBox<String> comboBox;

    private final List<String> elExpressions;

    private final Integer chooseIndex;

    private String lastSelected;

    public ChooseParam(PsiElement psiElement, List<String> elExpressions, Integer chooseIndex) {
        super(psiElement);
        this.elExpressions = elExpressions;
        this.chooseIndex = chooseIndex;
        this.comboBox = new ComboBox<>(elExpressions.toArray(new String[0]));
    }

    @Override
    public JComponent buildComponent(Runnable action) {

        comboBox.addActionListener(e -> {
            action.run();
        });
        comboBox.setSelectedIndex(0);


        FormBuilder formBuilder = FormBuilder.createFormBuilder();
        formBuilder.addLabeledComponent(getChooseParamName(), comboBox);

        return formBuilder.getPanel();
    }

    @Override
    public AbstractSqlEvent buildEvent() {
        String selected = comboBox.getSelectedItem().toString();
        String last = lastSelected;
        lastSelected = selected;
        return new UpdateTestEvent(getElExpression(selected), getElExpression(last));
    }

    @Override
    public void load(String cache) {
        lastSelected = cache;
        comboBox.setSelectedItem(cache);
    }

    private String getChooseParamName() {
        return "choose" + chooseIndex;
    }

    private String getElExpression(String expression) {
        return getChooseParamName() + "." + expression;
    }
}
